package camera;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import se.lth.cs.realtime.JThread;
import camerainterfaces.Axis211AInterface;

/**
 * A very small server that listens to HTTP GET and returns a picture from the
 * camera.
 * 
 */
public class TinyHttpServer extends JThread {
	private Axis211AInterface cam;
	private ServerSocket srv;
	private boolean run = true;

	/**
	 * @param srv
	 *            - ServerSocket to listen to.
	 * @param cam
	 *            - Camera to use.
	 */
	public TinyHttpServer(ServerSocket srv, Axis211AInterface cam) {
		this.cam = cam;
		this.srv = srv;
	}

	@Override
	public void run() {
		while (run) {
			try {
				HttpConnection conThread = new HttpConnection(srv.accept());
				conThread.start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * A connection thread that returns a picture.
	 * 
	 */
	private class HttpConnection extends JThread {
		private Socket channel;

		public static final String RETURN_IMAGE = "HTTP/1.0 200 OK\n"
				+ "Content-Type: image/jpeg\n" + "Pragma: no-cache\n"
				+ "Cache-Control: no-cache\n\n";

		public static final String METHOD_NOT_IMPLEMENTED = "HTTP/1.0 501 Method not implemented\n\n";

		public HttpConnection(Socket channel) {
			this.channel = channel;
		}

		@Override
		public void run() {
			String request = null;
			OutputStream out = null;
			byte[] jpeg = new byte[cam.getImageBufferSize()];
			try {
				out = channel.getOutputStream();
				BufferedReader read = new BufferedReader(new InputStreamReader(
						channel.getInputStream()));
				request = read.readLine();

				if (request.substring(0, 4).equals("GET ")) {
					int len = cam.getJPEG(jpeg, 0);
					out.write(RETURN_IMAGE.getBytes());
					out.write(jpeg, 0, len);
				} else {
					out.write(METHOD_NOT_IMPLEMENTED.getBytes());
				}
				out.flush();
				out.close();
				read.close();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
